# -*- encoding: utf8 -*-
from common.account import db as account_db
from event_rule.cp.marketing_event import (
    s2s_report,
    cps_report,
    cps_filter_report,
    daily_user_report,
    daily_device_report,
    summary_report
)
from common.es_core.report_creator import (
    get_daily_first_recharge,
    get_key_mapper_list,
    ReportCreator
)


def s2s_report_handler(cp_id, time_range):
    topic = cp_id
    idx_name = cp_id

    channel_list = account_db.get_distinct_channel_exists_app_id(merchant_name=topic)
    user_pool = None
    res = []
    for channel in channel_list:
        custom_filter = [
            {"exists": {"field": "_s2s_appid"}},
            {"term": {"_chn.keyword": channel}}
        ]
        channel_report = ReportCreator.create_report(user_pool=user_pool, start_time=time_range[0],
                                                     end_time=time_range[1], event_rule=s2s_report.S2S_REPORT_CONFIG,
                                                     index=idx_name, custom_filter=custom_filter, to_group=True)
        channel_report_list = channel_report['list']
        for elem in channel_report_list:
            # compatible old interface
            elem['s2s_appid'] = elem.pop('_s2s_appid')
        res.append({'channel': channel, 'list': channel_report['list'],
                    'channel_count': channel_report['total_count']})
    return res


def cp_cps_report_handler(cp_id, time_range):
    idx_name = cp_id
    channel_report = ReportCreator.create_report(user_pool=None, start_time=time_range[0], end_time=time_range[1],
                                                 event_rule=cps_report.CPS_REPORT_CONFIG, index=idx_name,
                                                 to_group=True)
    channel_report_list = channel_report['list']
    for elem in channel_report_list:
        # compatible old interface
        elem['chn'] = elem.pop('_chn')
    key_mapper = get_key_mapper_list(cps_report.CPS_REPORT_CONFIG.get("values"))
    res = [{'list': channel_report_list,
            'channel_count': channel_report['total_count'],
            'key_mapper': key_mapper}]
    return res


def cp_cps_filter_report_handler(cp_id, time_range, user_channel_ttls, banned_user_ids, banned_channels):
    idx_name = cp_id
    ttl_map = {channel_ttl['channel']: channel_ttl['ttl'] for channel_ttl in user_channel_ttls} \
        if user_channel_ttls else {}
    banned_channel_map = {banned_channel['channel']: banned_channel['max_user_id'] for banned_channel in
                          banned_channels} if banned_channels else {}
    channel_list_set = set(ttl_map.keys()).union(banned_channel_map.keys())
    custom_filter = []
    for channel in channel_list_set:
        channel_specify_term = {'term': {'_chn': channel}}
        channel_terms = [channel_specify_term]
        if channel in ttl_map:
            ttl_filter = {'range': {'_account_active_days': {'lte': ttl_map[channel]}}}
            channel_terms.append(ttl_filter)
        if channel in banned_channel_map:
            banned_filter = {'range': {'_user_id': {'gt': banned_channel_map[channel]}}}
            channel_terms.append(banned_filter)
        channel_filter = {'bool': {
            'should': [
                {'bool': {'must': channel_terms}},
                {'bool': {'must_not': channel_specify_term}},
            ],
            "minimum_should_match": 1}
        }
        custom_filter.append(channel_filter)
    if banned_user_ids:
        banned_user_filter = {'bool': {'must_not': {'terms': {'_user_id': banned_user_ids}}}}
        custom_filter.append(banned_user_filter)

    channel_report = ReportCreator.create_report(user_pool=None, start_time=time_range[0], end_time=time_range[1],
                                                 event_rule=cps_filter_report.CPS_FILTER_REPORT_CONFIG,
                                                 index=idx_name, custom_filter=custom_filter, to_group=True)
    channel_report_list = channel_report['list']
    for elem in channel_report_list:
        # compatible old interface
        elem['chn'] = elem.pop('_chn')
    key_mapper = get_key_mapper_list(cps_filter_report.CPS_FILTER_REPORT_CONFIG.get("values"))
    res = {'list': channel_report_list,
           'channel_count': channel_report['total_count'],
           'key_mapper': key_mapper}
    return res


def cp_daily_user_report(cp_id, chn_list, time_range):
    idx_name = cp_id
    key_mapper = get_key_mapper_list(daily_user_report.DAILY_USER_REPORT.get("values"))

    custom_filter = None
    if chn_list:
        custom_filter = [{"terms": {"_chn.keyword": chn_list}}]
    report = ReportCreator.create_report(user_pool=None, start_time=time_range[0], end_time=time_range[1],
                                         event_rule=daily_user_report.DAILY_USER_REPORT, index=idx_name,
                                         custom_filter=custom_filter, to_group=True)
    report.update({"key_mapper": key_mapper})
    return report


def cp_daily_device_report(cp_id, chn_list, time_range):
    idx_name = cp_id
    key_mapper = get_key_mapper_list(daily_device_report.DAILY_DEVICE_REPORT.get("values"))
    custom_filter = None
    if chn_list:
        custom_filter = [{"terms": {"_chn.keyword": chn_list}}]
    report = ReportCreator.create_report(user_pool=None, start_time=time_range[0], end_time=time_range[1],
                                         event_rule=daily_device_report.DAILY_DEVICE_REPORT, index=idx_name,
                                         custom_filter=custom_filter, to_group=True)
    report.update({"key_mapper": key_mapper})
    return report


def cp_summary_report(app_name, time_range):
    report = ReportCreator.create_report(user_pool=None, start_time=time_range[0], end_time=time_range[1],
                                         event_rule=summary_report.DAILY_USER_REPORT, index=app_name)

    dynamic_argument_dct = get_daily_first_recharge(app_name, time_range[0], time_range[1])
    dynamic_argument_dct.update({
        'total_choushui_amount': report.get('profit')
    })
    game_report = ReportCreator.create_report(user_pool=None, start_time=time_range[0], end_time=time_range[1],
                                              event_rule=summary_report.CP_GAME_REPORT, index=app_name,
                                              dynamic_argument_dct=dynamic_argument_dct, to_group=True)
    lottery_report = ReportCreator.create_report(user_pool=None, start_time=time_range[0], end_time=time_range[1],
                                                 event_rule=summary_report.LOTTERY_GAME_REPORT, index=app_name,
                                                 dynamic_argument_dct=dynamic_argument_dct, to_group=True)
    game_report['list'] = [dict(('game_id', v) if k == 'cp_game_third_type' else (k, v)
                                for k, v in item.items()) for item in game_report['list']]
    game_report['list'] += [dict(('game_id', v) if k == 'cp_lottery_sub_type' else (k, v)
                                 for k, v in item.items()) for item in lottery_report['list']]
    game_report['total_count'] += lottery_report['total_count']
    key_mapper = get_key_mapper_list(summary_report.DAILY_USER_REPORT.get("values"))
    return {"summary": report, "game": game_report, "key_mapper": key_mapper}
